package com.mindmap.model;

import java.awt.*;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class Node implements Serializable {
    private static final long serialVersionUID = 1L;
    private String text;
    private Node parent;
    private List<Node> children;
    private Rectangle bounds;
    private Color color;
    private boolean selected;

    public Node(String text) {
        this.text = text;
        this.children = new ArrayList<>();
        this.bounds = new Rectangle(0, 0, 100, 40);
        this.color = Color.WHITE;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public Node getParent() {
        return parent;
    }

    public void setParent(Node parent) {
        this.parent = parent;
    }

    public List<Node> getChildren() {
        return children;
    }

    public void addChild(Node child) {
        child.setParent(this);
        children.add(child);
    }

    public void removeChild(Node child) {
        children.remove(child);
    }

    public Rectangle getBounds() {
        return bounds;
    }

    public void setBounds(Rectangle bounds) {
        this.bounds = bounds;
    }

    public void setLocation(Point location) {
        bounds.setLocation(location);
    }

    public Color getColor() {
        return color;
    }

    public void setColor(Color color) {
        this.color = color;
    }

    public boolean isSelected() {
        return selected;
    }

    public void setSelected(boolean selected) {
        this.selected = selected;
    }

    public boolean contains(Point point) {
        return bounds.contains(point);
    }

    public Point getConnectionPoint(Node child) {
        Rectangle parentBounds = this.getBounds();
        Rectangle childBounds = child.getBounds();
        
        int parentCenterX = parentBounds.x + parentBounds.width / 2;
        int parentCenterY = parentBounds.y + parentBounds.height / 2;
        
        int childCenterX = childBounds.x + childBounds.width / 2;
        int childCenterY = childBounds.y + childBounds.height / 2;
        
        // 计算连接点位于父节点哪一侧
        if (childCenterX < parentBounds.x) { // 左侧
            return new Point(parentBounds.x, parentCenterY);
        } else if (childCenterX > parentBounds.x + parentBounds.width) { // 右侧
            return new Point(parentBounds.x + parentBounds.width, parentCenterY);
        } else if (childCenterY < parentBounds.y) { // 上方
            return new Point(parentCenterX, parentBounds.y);
        } else { // 下方
            return new Point(parentCenterX, parentBounds.y + parentBounds.height);
        }
    }
    
}
